package com.wyg.demo.controller;

import com.wyg.demo.common.CommonResult;
import com.wyg.demo.common.OperateMenu;
import com.wyg.demo.common.OperateType;
import com.wyg.demo.domain.ExcelData;
import com.wyg.demo.domain.vo.ExcelDataVo;
import com.wyg.demo.service.ExcelDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author ygWen
 * @Description 共享申请单 controller
 * @date 2022/1/1
 */
@Slf4j
@RestController
public class ExcelDataController {
    
    @Autowired
    private ExcelDataService excelDataService;
    
    @Value("${deposeFilesDir}")
    private String deposeFilesDir;

    /**
     * 上传excel文件并将数据解析入库
     * @param file 上传的文件
     * @return 结果
     */
    @PostMapping("/excelFile/import")
    @OperateType(menu = OperateMenu.MENU_EXCEL_DATA, operateType = OperateMenu.OPERATE_IMPORT)
    public CommonResult<Void> fileUpload(@RequestParam("fileName") MultipartFile file) throws IOException {
        String filePath = excelDataService.fileUpload(file);
        excelDataService.excelRead(filePath);
        return CommonResult.success();
    }

    /**
     * 将数据写入excel并下载
     * @param response 响应对象
     * @param excelDataVo 条件
     */
    @PostMapping("/excelFile/download")
    @OperateType(menu = OperateMenu.MENU_EXCEL_DATA, operateType = OperateMenu.OPERATE_DOWNLOAD)
    public CommonResult<Object> fileDownload(HttpServletResponse response,
                                             @RequestBody(required = false) ExcelDataVo excelDataVo) 
                                throws IOException {
        List<ExcelData> excelDataList = excelDataService.selectDataList(excelDataVo);
        String fileName = excelDataService.excelSimpleWrite(excelDataList);
        excelDataService.downloadExcel(response, fileName);
        return CommonResult.success();
    }

    /**
     * excel文件模板下载
     * @param response 响应对象
     * @return
     */
    @PostMapping("/excelFileTemplate/download")
    @OperateType(menu = OperateMenu.MENU_EXCEL_DATA, operateType = OperateMenu.OPERATE_DOWNLOAD)
    public CommonResult fileTemplateDownload(HttpServletResponse response) throws IOException {
        excelDataService.downloadExcelTemplate(response);
        return CommonResult.builder().code(200).message("下载成功").build();
    }
}
